/**
 * Created by zhaocong on 2016/8/3.
 * 干货挑战，上传小票
 */
var cc = window.cc || {};
cc.program = new function () {
  var self = this;

  // 调整页面大小
  var docEl = document.documentElement,
      resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
      recalc = function () {
        docEl.style.fontSize = 20 * (docEl.clientWidth / 375) + 'px';
        document.body.style.minHeight = docEl.clientHeight + 'px';
      };
  window.addEventListener(resizeEvt, recalc, false);
  document.addEventListener('DOMContentLoaded', recalc, false);

  /**
   * 抽奖
   * TODO Ajax请求随机奖品
   */
  self.lot = function () {
    var _this = this;
    $.ajax({
      url: '',
      type: 'get',
      success: function (data) {
        self.rotate('68');　　// 奖金
        $(_this).off('tap');
      },
      erro: function () {
        alert('链接超时');
      }
    });
  };
  var info = {
    '6.8': 132,
    '16.8': 226,
    '26.8': 271,
    '46.8': 178,
    '68': 360
  };
  self.rotate = function (deg) {
    var late = 720 + info[deg];
    $('.pointer').css({
      'webkitTransform': 'rotate(' + late + 'deg)',
      'transform': 'rotate(' + late + 'deg)',
      'webkitTransition': 'all 2.4s cubic-bezier(0.20 , 0.65 , 0.01 , 0.95)',
      'transition': 'all 2.4s cubic-bezier(0.20 , 0.65 , 0.01 , 0.95)'
    });
    setTimeout(function () {
      $('#money').html('￥' + deg);
      $('.winning').show();
    }, 3000);
  };

  /**
   * 地址联动
   * @param adr 关键字，用于后台判断value的属性
   * @param value
   * @param aim DomID 用于更新下拉框
   */
  self.shmd = function (adr, value, aim) {
    var data = {a: adr, v: value},
        arr = [],
        _html = [];
    // TODO 通过关键字查询地址
    $.ajax({
      url: 'data/city.json',
      type: 'GET',
      data: data,
      success: function (data) {
        arr = data.arr;
        $.each(arr, function (i, el) {
          _html.push('<option value="' + el + '">' + el + '</option>');
        });
        _html.unshift('<option value="">请选择</option>');
        $(aim).html(_html.join(''));
      }
    });
  };

};


/**
 * 首页
 */
cc.index = function () {
  // console.log('首页');
};


/**
 * 上传小票
 */
cc.start = function () {
  // 设置选择时间插件
  $('#datetime').mdater({
    minDate: new Date(2016, 0, 4)
  });

  // 上传图片 提交表单
  var imageload = new ImageUpload(option);
  // imageload.init();
  // 测试
  imageload.test();

  // 加载卖场
  stores.init();

  // 加载门店
  md.init();


  // 检索地址和门店
  $('#stores').on('valuechange', function () {
    $(this).val() && cc.program.shmd('stores', $(this).val(), '#province');
  });
  $('#province').on('change', function () {
    $(this).val() && cc.program.shmd('province', $(this).val(), '#city');
  });
  $('#city').on('change', function () {
    $(this).val() && cc.program.shmd('city', $(this).val(), '#store');
  });
};


/**
 * 抽奖页
 */
cc.lottery = function () {
  $('.action').on('tap', cc.program.lot);
};


/**
 * 审核页面
 */
cc.check = function () {
  // 进度条
  var _point = $('.point'),
      size = _point.data('size');
  _point.css('left', size);
  $('.timeline .before').width(size);

  // 分享
  $('.share').tap(function () {
    $(this).hide();
  });

  // 页面状态
  var page = $('body').data('page'),
      _ctit = $('.c-tit'),
      _wite = $('.lin-wite');
  if(page == '1'){
    _ctit.removeClass('sccg').addClass('shcg');
    _wite.remove();
    $('.stu1').show().siblings('.info').hide();
  }else if(page == 2){
    _ctit.removeClass('sccg').addClass('shsb');
    _wite.remove();
    $('.stu2').show().siblings('.info').hide();
    $('#showsub').show();
    upimg();
  }

  // 上传图片
  function upimg() {
    $('#showsub').tap(function () {
      $('.pop-in').show();
    });
    $('.pop-mask').tap(function () {
      $('.pop-in').hide();
    });

    var imageload = new ImageUpload(option1);
    // imageload.init();
    // 测试
    imageload.test();
  }
};


/**
 * 选择卖场
 */
var stores = {
  storebox: $('.mc'),
  storecrl: $('#stores'),
  show: function () {
    stores.storebox.show();
    $('body,html').addClass('ovfHiden');
  },
  hideen: function () {
    stores.storebox.hide();
    $('body,html').removeClass('ovfHiden');
  },
  layer: function () {
    var val = $(this).children('span').text();
    stores.storecrl.val(val);
    stores.hideen();
    $('#stores').trigger('valuechange');
  },
  // TODO 加载更多 添加搜索结果，或者显示全部内容
  moremarket: function () {
    var _ul = $('.st-ul'),
        top = _ul.scrollTop(),
    // load
        _html = '<li class="layer"><span class="st-val">--加载--</span></li>';

    $('.moremarket-list').html(_html);
    _ul.scrollTop(top + 20);
  },
  init: function () {
    var _this = this;
    $(_this.storecrl).on('tap', _this.show);
    $('.stores-mask').on('tap', _this.hideen);
    $('.mc .st-ul').on('tap', '.layer', _this.layer);
    $('#moremarket').on('tap', _this.moremarket);
  }
};


/**
 * 选择门店
 */
var md = {
  storebox: $('.md'),
  storecrl: $('#store'),
  show: function () {
    md.storebox.show();
    $('body,html').addClass('ovfHiden');
  },
  hideen: function () {
    md.storebox.hide();
    $('body,html').removeClass('ovfHiden');
  },
  layer: function () {
    var val = $(this).children('span').text();
    md.storecrl.val(val);
    md.hideen();
  },
  // TODO 加载更多 添加搜索结果，或者显示全部内容
  moremarket: function () {
    var _ul = $('.st-ul'),
        top = _ul.scrollTop(),
    // load
        _html = '<li class="layer"><span class="st-val">--加载--</span></li>';

    $('.moremarket-list').html(_html);
    _ul.scrollTop(top + 20);
  },
  init: function () {
    var _this = this;
    $(_this.storecrl).on('tap', _this.show);
    // $('.stores-mask').on('tap', _this.hideen);
    $('.md .st-ul').on('tap', '.layer', _this.layer);
    // $('#moremarket').on('tap', _this.moremarket);
  }
};



/**
 * option 上传小票默认设置
 */
var option = {
  // 测试上传图片的地址
  test: '/yuezi/localUpload',
  // 表单提交地址
  url: '/yuezi/receipt',

  images: [], // 保存上传的图片url
  addbtn: '', // 保存上传按钮状态

  imgbtn: $('.addbtn'), // 上传图片的按钮
  subbtn: $('#sub'), // 提交表单按钮
  product: [],//产品信息
  lat: $('#lat').val(), //经纬度
  lng: $('#lng').val(),
  networkType: $('#networkType').val(),

  // 显示当前状态
  status: function (data) {
    layer.open({
      content: data,
      style: 'background-color:#129d93; color:#fff;',
      time: 2
    });
  },
  imgbeforeSend: function () {
    layer.open({
      content: '<i class="loading"></i>小票飞速上传中...',
      style: 'background-color:#129d93; color:#fff;',
      shadeClose: false
    });
  },
  imgsuccess: function () {
    layer.closeAll();
    if (this.images.length < 3) {
      $('#load-info').html('<div style="height:5px;"></div><span class="fn12 green">请继续上传或立即提交</span>');
    } else {
      $('#load-info').html('<div style="height:5px;"></div><span class="fn12 green">小票上传完成</span>');
    }
    $(this.addbtn).off('tap');
  },
  imgerr: function () {
    this.status('上传图片失败');
  },
  preview: function () {
    var that = this;
    wx.previewImage({
      current: this.option.images[0], // 当前显示图片的http链接
      urls: this.option.images// 需要预览的图片http链接列表
    });
  },
  case: function () {
    var that = this;
    var stores = $.trim($('#stores').data('id')),
        p_id = $('.p_id'),
        p_num = $('.p_num'),
        datetime = $.trim($('#datetime').val());
    $.each(p_num, function (index, val) {
      if ($(val).val() != '0') {
        that.product[index] = ([$(val).val(), p_id.eq(index).val()]);
      }
    });

    if (stores && datetime && this.images.length && this.product.length) {
      return {
        stores: stores,
        datetime: datetime,
        images: this.images,
        product: this.product,
        lat: this.lat,
        lng: this.lng,
        networkType: this.networkType
      };
    } else {
      this.status('请将数据填写完整');
      return false;
    }
  },
  formbeforeSend: function (e) {
    this.status('<i class="loading"></i>表单提交中');
  },
  formsuccess: function (receipt_id) {
    this.status('表单提交成功');
    window.location.href = '/yuezi/check?receipt_id=' + receipt_id;
  }
};

// 重新上传小票
var option1 = {
  // 测试上传图片的地址
  test: '/yuezi/localUpload',
  // 表单提交地址
  url: '/yuezi/reUpload',

  images: [], // 保存上传的图片url
  addbtn: '', // 保存上传按钮状态
  receipt_id: $('#receipt_id').val(),
  imgbtn: $('.addbtn'), // 上传图片的按钮
  subbtn: $('#sub'), // 提交表单按钮

  // 显示当前状态
  status: function (data) {
    layer.open({
      content: data,
      style: 'background-color:#129d93; color:#fff;',
      time: 2
    });
  },
  imgbeforeSend: function () {
    layer.open({
      content: '<i class="loading"></i>小票飞速上传中...',
      style: 'background-color:#129d93; color:#fff;',
      shadeClose: false
    });
  },
  imgsuccess: function () {
    layer.closeAll();
    if (this.images.length < 3) {
      $('#load-info').html('<div style="height:5px;"></div><span class="fn12 green">请继续上传或立即提交</span>');
    } else {
      $('#load-info').html('<div style="height:5px;"></div><span class="fn12 green">小票上传完成</span>');
    }
    $(this.addbtn).off('tap');
  },
  imgerr: function () {
    this.status('上传图片失败');
  },
  case: function () {
    if (this.images.length) {
      return {
        images: this.images,
        receipt_id: this.receipt_id
      };
    } else {
      this.status('请上传图片');
      return false;
    }
  },
  formbeforeSend: function (e) {
    this.status('<i class="loading"></i>表单提交中');
  },
  formsuccess: function (receipt_id) {
    window.location.href = '/yuezi/check?receipt_id=' + receipt_id;
  }
};


/**
 * 上传图片，提交表单，模拟微信上传图片
 * @constructor
 *
 */
function ImageUpload(option) {
  this.option = option;
  // 多图上传时保留的上一张图片名 避免重复上传
  this.lastimg = '';
}

/**
 * 1.初始化默认调用方法。
 */
ImageUpload.prototype.init = function () {
  var that = this;
  that.event();
  that.option.imgbtn.on('tap', function (e) {
    that.wxImg(that);
    that.option.addbtn = e.target;
  });
  $('.addbtn-box').on('tap', '.up-img', that.option.preview);
};

/**
 * 2.测试时调用方法
 */
ImageUpload.prototype.test = function () {
  var that = this;
  that.event();
  that.testInit();
  that.option.imgbtn.on('tap', function (e) {
    that.testImg(e, that);
    that.option.addbtn = e.target;
  });
};

/**
 * 3.用户行为 初始化操作
 */
ImageUpload.prototype.event = function () {
  var that = this;
  // 提交按钮
  that.option.subbtn.on('click', function (e) {
    e.preventDefault();
    that.sub(e, that);
  });
};


/**
 * 5.提交表单
 * @param e
 * @param that
 */
ImageUpload.prototype.sub = function (e, that) {
  var data = that.option.case();
  if (data) {
    $.ajax({
      url: that.option.url,
      type: 'post',
      data: data,
      beforeSend: function () {
        e.target.disabled = true;
        that.option.formbeforeSend(e);
      },
      success: function (data) {
        var obj = eval('(' + data + ')');
        e.target.disabled = false;
        that.option.formsuccess(obj.receipt_id);
      },
      error: function () {
        e.target.disabled = false;
        that.option.status('上传图片失败');
      }
    });
  }
};

/**
 * 6.微信上传
 * @param e
 * @param that
 */
ImageUpload.prototype.wxImg = function (that) {
  // 调用微信图片接口
  wx.chooseImage({
    count: 1, // imgCount
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    isShowProgressTips: 0,
    success: function (res) {
      that.option.imgbeforeSend();
      $(that.option.addbtn).css('background', 'url(' + res.localIds[0] + ') center/cover').addClass('up-img');
      wxUpload(res.localIds.toString());
    }
  });
  // 上传图片
  function wxUpload(id) {
    wx.uploadImage({
      localId: id, // 需要上传的图片的本地ID，由chooseImage接口获得
      isShowProgressTips: 0, // 默认为1，显示进度提示
      success: function (res) {
        var serverId = res.serverId; // 返回图片的服务器端ID
        $.getJSON(info.host + info.dir + "/uploadImg", {"mediaId": serverId}, function (data) {
          if (data.errcode == 0) {
            that.addImage(data.url, that);
          } else {
            that.option.imgerr();
          }
        });
      },
      fail: function (res) {
        alert(JSON.stringify(res));
        that.option.imgerr();
      }
    });
  }
};

/**
 * 7.模拟微信上传 初始化时添加iframe组件
 */
ImageUpload.prototype.testInit = function () {

  var tmp = document.createElement('iframe');
  tmp.id = 'tmpIframe';
  tmp.name = 'tmpIframe';
  tmp.style.display = 'none';
  document.body.appendChild(tmp);

  var form = document.createElement('form');
  form.id = 'tmpFileForm';
  form.action = this.option.test;
  form.method = "post";
  form.target = "tmpIframe";
  form.enctype = "multipart/form-data";
  form.style.display = 'none';
  document.body.appendChild(form);

  var azFile = document.createElement("input");
  azFile.name = "azFile";
  azFile.id = "azFile";
  azFile.type = "file";
  document.getElementById("tmpFileForm").appendChild(azFile);
};

/**
 * 8.模拟微信上传
 * @param e
 * @param that
 */
ImageUpload.prototype.testImg = function (e, that) {
  var file = $('#azFile'),
      fet = false; // 禁止反复触发change

  file.trigger('click');
  file.on('change', function () {
    if (file.val() != that.lastimg && file.val()) {
      $("#tmpFileForm").submit();
      that.option.imgbeforeSend();
      that.lastimg = file.val();
      fet = true;
    }
  });

  $('#tmpIframe').on('load', function () {
    /**
     * 获取返回的数据
     * @type {*|jQuery}
     */
    var data = $.trim($(window.frames['tmpIframe'].document.body).find('p').html());
    if (fet) data ? that.addImage(data, that) : that.option.imgerr();
    $(e.target).css({'background': 'url(' + window.URL.createObjectURL(file.get(0).files[0]) + ') center/cover'});
  });
};

/**
 * 9.将返回图片的地址添加到images中,并判断图片上传的张数
 * @param data 图片地址
 * @param e
 * @param that
 */
ImageUpload.prototype.addImage = function (data, that) {
  that.option.images.push(data);
  that.option.imgsuccess();
};

